import { defineConfig } from 'vite'
import legacy from '@vitejs/plugin-legacy'
import viteCompression from 'vite-plugin-compression'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import vitePluginHtml from 'vite-plugin-html'
import eslintPlugin from 'vite-plugin-eslint'
import ViteComponents, { AntDesignVueResolver } from 'vite-plugin-components'
import config from './src/config/index.js'

export default defineConfig(({ command, mode }) => {
  console.log(`${import.meta.env}`, mode, command)
  const IS_DEV = mode === 'development'
  const IS_PRO = mode === 'production'
  const base = IS_PRO ? './' : './'
  let customConfig = {}
  if (IS_DEV) {
    // 开发环境 独有配置
    customConfig.plugin = [
      eslintPlugin({
        cache: false
      })
    ]
  } else {
    // 打包环境 独有配置
    customConfig.plugin = [viteCompression()]
  }
  return {
    ...customConfig,
    base,
    // publicDir: 'static',
    server: {
      host: '0.0.0.0',
      port: '2829',
      strictPort: false,
      // open: '/',
      fs: {
        // 可以为项目根目录的上一级提供服务
        allow: ['..']
      },
      proxy: {
        // 下面是选项写法，例子
        '/api': {
          target: 'http://jsonplaceholder.typicode.com',
          changeOrigin: true,
          rewrite: path => path.replace(/^\/api/, '')
        },
        ...Object.values(config.proxy).reduce((pre, cur) => ({ ...pre, [cur['prefix']]: cur['rule'] }), {})
      },
      hmr: {
        overlay: true
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: '' // '@import "./src/style/app/common.scss";' // 添加公共样式
        },
        less: {
          modifyVars: {
            // 用于全局导入，以避免需要单独导入每个样式文件。
            // reference:  避免重复引用
            hack: `true; @import (reference) "${resolve('src/style/app/variables.less')}";
                         @import (reference) "${resolve('src/style/app/mixin.less')}";
                         @import (reference) "${resolve('src/style/app/transition.less')}";`
          },
          javascriptEnabled: true
        }
      }
    },
    define: {
      __APP_VERSION__: JSON.stringify('你好，世界')
    },
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src'),
        '+': resolve(__dirname, 'src/assets'),
        '~': resolve(__dirname, 'node_modules'),
        '~vuex-helper': resolve(__dirname, 'src/store/plugins/vuex-helper.js')
      },
      extensions: ['.vue', '.mjs', '.js', '.ts', '.jsx', '.tsx', '.json']
    },
    build: {
      brotliSize: false,
      polyfillModulePreload: true, // 用于决定是否自动注入 module preload 的 polyfill.
      // outDir: resolve(__dirname, 'build') // 默认打包到 根目录下dist中
      assetsInlineLimit: 4096 // 小于此阈值的导入或引用资源将内联为 base64 编码，以避免额外的 http 请求。设置为 0 可以完全禁用此项。
    },
    plugins: [
      vue(),
      vitePluginHtml({
        inject: {
          data: {
            title: '统一门户',
            injectScript: ''
          }
        },
        minify: true
      }),
      /*Vite 按需加载组件*/
      ViteComponents({
        customComponentResolvers: [AntDesignVueResolver({ importStyle: false })]
      }),
      legacy({
        additionalLegacyPolyfills: ['regenerator-runtime/runtime'] // 面向IE11时需要此插件
      }),
      ...customConfig.plugin
    ]
  }
})
